package utils

import (
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/gorm"
	"seat-service/model"
)

var Casbin *CasbinMethod

type CasbinMethod struct {
	Enforcer *casbin.Enforcer
	Adapter  *gormadapter.Adapter
}

type User struct {
	UserCode  string   `json:"user_code"`
	RoleNames []string `json:"role_names"`
}

// InitCasbinGorm 初始化Casbin Gorm适配器
func InitCasbinGorm(db *gorm.DB) (*CasbinMethod, error) {
	// 创建Gorm适配器
	a, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		return nil, err
	}
	// 迁移数据库表，使用新的 CasbinRuleExtended 模型
	err = db.AutoMigrate(&model.CasbinRuleExtended{})
	if err != nil {
		return nil, err
	}
	// 创建Casbin Enforcer，指定自定义Model文件
	enforcer, err := casbin.NewEnforcer("./model.config", a)
	if err != nil {
		return nil, err
	}
	Casbin = &CasbinMethod{Adapter: a, Enforcer: enforcer}
	return &CasbinMethod{Adapter: a, Enforcer: enforcer}, nil
}
